<?php

/**
 *
 * Class UserController
 * @author dashan
 * @date 2022-05
 */

namespace app\agent\controller;

use app\common\model\UserModel;
use think\facade\Request;

class UserController extends BaseController {
    /**
     *  用户列表页面
     * @return mixed
     */
    public function index() {
        return $this->fetch();
    }

    /**
     * 用不列表数据
     * @return \think\response\Json
     */
    public function getlist() {
        $searchid   = Request::param("id");
        $account    = Request::param("account");
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $page       = Request::param("page");
        $limit      = Request::param("limit");

        // 代理的下级用户id
        $subordinate_uid = $this->get_subordinate_uid();

        $where[]   = ['id', 'in', $subordinate_uid];
        $wherelike = '';

        if ($searchid) {
            $where[] = ['id', '=', $searchid];;
        }
        if ($start_time) {
            $where[] = ["regist_time", ">=", $start_time];
        }
        if ($end_time) {
            $where[] = ["regist_time", ">=", $end_time];
        }

        if ($account != '') {
            $wherelike = "account like '{$account}%' or mobile like '{$account}%'";
        }

        $field = 'id,account,mobile,nick_name,avatar,diamond,online_status,sharing_ratio,regist_time';

        $userlist = UserModel::where($where)->where($wherelike)->field($field)
            ->with([
                'profile',
                'anchorAuth'   => function ($query) {
                    $query->where('status', 1)->withField('uid,real_name');
                }, 'orderInfo' => function ($query) {
                    $query->where('pay_status', 1)->group('uid')->withField('uid,sum(pay_amount) as pay_amount');
                },
            ])
            ->order('regist_time desc')
            ->limit(($page - 1) * $limit, $limit)
            ->select();

        if (count($userlist) > 0) {
            $count = UserModel::where($where)->where($wherelike)->count("id");

            foreach ($userlist as &$item) {
                if ($item->mobile) {
                    $item->mobile = substr_replace($item->mobile, "******", 3, 6);
                }
            }

            return json(["code" => 0, "msg" => "", "data" => $userlist, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 修改分红比例
     * @return \think\response\Json|void
     */
    function edit_ratio() {
        $uid = Request::param("uid", 0);
        // 分成比例
        $sharing_ratio = Request::param("sharing_ratio", 0);
        if ($uid < 1) {
            return self::bulidFail("参数错误，请刷新页面重试");
        }
        //分红数值验证
        if ($sharing_ratio > 0 && ($sharing_ratio > 100 || $sharing_ratio < 1)) {
            return self::bulidFail("分红比例不得大于100且不小于1");
        }

        $user_model = UserModel::get($uid);
        if (!$user_model) {
            return self::bulidFail("用户不存在");
        }

        // 代理的下级用户id
        $subordinate_uid = $this->get_subordinate_uid();
        if (!in_array($uid, $subordinate_uid)) {
            return self::bulidFail("修改失败，请刷新页面重试");
        }

        $user_model->sharing_ratio = $sharing_ratio;
        if ($user_model->save()) {
            // 清理主播缓存
            UserModel::delAnchorCache();

            return self::bulidSuccess([], "编辑成功");
        }
        return self::bulidFail();
    }

    /**
     * 获取代理五层下级
     * @param $agent_ids 需要查询的用户ID
     * @param array $all_uid 存储查询结果
     * @param int $max 查询几级
     * @param int $level 当前查询的级别
     * @return array|mixed
     */
    protected function get_subordinate_uid($agent_ids = null, $all_uid = [], $max = 5, $level = 1) {
        if (is_null($agent_ids)) {
            $agent_ids = $this->userinfo->id;
        }

        $user_model = new UserModel();
        $result     = $user_model->whereIn('agentid', $agent_ids)->column('id');

        if (empty($result) || $level > $max) {
            return array_unique($all_uid);
        }

        $all_uid = array_merge($all_uid, $result);
        $level++;

        return $this->get_subordinate_uid($result, $all_uid, $max, $level);
    }
}